﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace VSA.Applications
{
    public partial class FunctionInfoForm : Form
    {
        public String DeleteList { get; set; }
        public DataTable FunctionTable { get; set; }
        public PersonInfoForm ContactPersonForm { get; set; }

        public FunctionInfoForm()
        {
            InitializeComponent();
            this.gv_Function.DataSource = WebServiceFactory.GetService().GetAllFunctionList().Tables[0];
            this.FunctionTable = this.gv_Function.DataSource as DataTable;
        }

        private void gv_Function_UserDeletingRow(object sender, DataGridViewRowCancelEventArgs e)
        {
            if (String.IsNullOrEmpty(DeleteList))
            {
                DeleteList = e.Row.Cells[0].Value.ToString();
            }
            else
            {
                DeleteList += "|" + e.Row.Cells[0].Value.ToString();
            }
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            String newString = String.Empty;
            String updateString = String.Empty;
            String deleteString = String.Empty;

            foreach (DataRow dr in FunctionTable.Rows)
            {
                if (dr.RowState == DataRowState.Added)
                {
                    if (String.IsNullOrEmpty(newString))
                    {
                        newString = dr["FunctionName"].ToString();
                    }
                    else
                    {
                        newString += "|" + dr["FunctionName"].ToString();
                    }
                }
                else if (dr.RowState == DataRowState.Modified)
                {
                    if (String.IsNullOrEmpty(updateString))
                    {
                        updateString = dr["Did"].ToString() + ";" + dr["FunctionName"].ToString();
                    }
                    else
                    {
                        updateString += "|" + dr["Did"].ToString() + ";" + dr["FunctionName"].ToString();
                    }
                }
            }

            DataSet ds = WebServiceFactory.GetService().SaveFunctionData(newString, updateString, this.DeleteList);
            this.ContactPersonForm.FunctionDataSource = ds.Tables[0];
            this.ContactPersonForm.BuildFunctionBox();
            MessageBox.Show(
                "Save successful",
                "System Information",
                MessageBoxButtons.OK,
                MessageBoxIcon.Information
                );
            this.Dispose();
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            this.Dispose();
        }
    }
}
